import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Button, Form, Input, message, Modal } from 'antd';
import React from 'react';
import { useNavigate } from 'react-router-dom';

import api from '@/apis/api';
import { Logger } from '@/components/useLogger';
import localINFO from '@/utils/localInfo';
import LocalInfo from '@/utils/localInfo';

import styles from '../styles.module.less';
const ResetButton: React.FC = () => {
  const navigate = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();
  const [visible, setVisible] = React.useState(false);

  const [form] = Form.useForm();

  const queryClient = useQueryClient();

  const ResetDevice = useMutation({
    mutationFn: (params: any) => api.ResetDevice(params),
    onSuccess: (res: any) => {
      if (res?.success) {
        messageApi.success({
          content: '恢复出厂设置成功! 请重新登录',
          key: 'resetting',
        });
        navigate('/login');
      } else {
        message.error(`恢复出厂设置失败, ${res?.message}`);
      }
    },
    onError: (error: any) => {
      Logger(error);
      messageApi.error({
        content: '恢复出厂设置失败!',
        key: 'resetting',
      });
    },
    onSettled: () =>
      queryClient.invalidateQueries({
        queryKey: ['getDeviceInfo', 'getDeviceStatus'],
      }),
    mutationKey: ['getDeviceInfo', 'getDeviceStatus'],
  });

  const resetSetting = () => {
    messageApi.info({
      content: '正在恢复出厂设置，请稍等...',
      key: 'resetting',
    });
  };

  const handleVerivyOk = async () => {
    await form.validateFields();
    const adminPassword = form.getFieldValue('adminPassword');
    ResetDevice.mutate({
      password: adminPassword,
    });
    resetSetting();
    form.resetFields();
    setVisible(false);
  };
  const handleVerifyCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  return (
    <>
      <div className={styles.InitializationButton1}>
        {contextHolder}
        <Button
          type="default"
          onClick={() => setVisible(true)}
          className={styles.Button}
          disabled={LocalInfo.getRoleId() === 2}
        >
          恢复出厂设置
        </Button>
      </div>
      <Modal
        title="验证管理员密码"
        open={visible}
        onOk={handleVerivyOk}
        onCancel={handleVerifyCancel}
        cancelText="取消"
        okText="确定"
        destroyOnClose
        okButtonProps={{ disabled: localINFO.getRoleId() !== 1 }}
      >
        <Form
          form={form}
          preserve={false}
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600, marginTop: 24, marginBottom: 24, width: 450 }}
          autoComplete="off"
        >
          <Form.Item
            label="管理员密码"
            name="adminPassword"
            rules={[{ required: true, message: '请输入管理员密码！' }]}
            style={{ marginBottom: 0 }}
          >
            <Input.Password placeholder="请输入管理员密码" autoComplete="new-password" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default React.memo(ResetButton);
